package com.cloudptt.wp.ui;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.cloudptt.api.comm.CauseCont;
import com.cloudptt.api.comm.CommDlg;
import com.cloudptt.api.comm.Const;
import com.cloudptt.api.product.NetworkListener;
import com.cloudptt.api.product.Product;
import com.cloudptt.api.product.ProductConst;
import com.cloudptt.api.product.adapter.GCallEventAdapter;
import com.cloudptt.api.product.adapter.ICallInfoDesc;
import com.cloudptt.api.product.func.call.CallAttr;
import com.cloudptt.api.product.func.message.MsgListener;
import com.cloudptt.api.product.func.sys.SysStateInfo;
import com.cloudptt.api.product.func.sys.listener.SysListener;
import com.cloudptt.api.product.log.Log;
import com.cloudptt.api.product.operator.MsgOperator;
import com.cloudptt.api.product.update.UpdateListener;
import com.cloudptt.wp.R;
import com.cloudptt.wp.ScreenManager;
import com.cloudptt.wp.SysApplication;
import com.cloudptt.wp.ui.address.workspace.WorkspaceFragment;
import com.cloudptt.wp.ui.message.IMsgCallBack;
import com.cloudptt.wp.ui.message.MessageFragment;
import com.cloudptt.wp.ui.message.SessionActivity;
import com.cloudptt.wp.ui.more.SettingActivity;
import com.cloudptt.wp.ui.views.GroupcallStateLayout;
import com.cloudptt.wp.ui.views.OfflineStateLayout;
import com.cloudptt.wp.ui.views.PTTLayout;
import com.cloudptt.wp.ui.views.listener.DialListener;
import com.mcptt.config.model.McIdInfo;
import com.mcptt.config.user.profile.UserProfile;
import com.mcptt.db.model.AddrInfo;
import com.mcptt.db.model.HistoryInfo;
//import com.mcptt.http.operator.IHttpAddrOpCb;
import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.ContentObserver;
import android.graphics.Color;
import android.hardware.camera2.CameraManager;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.TriangularPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.CommonPagerTitleView;

import org.pjsip.PjCameraInfo2;

public class HomeActivity extends AppCompatActivity implements View.OnClickListener, CallBack, SysListener
		, NetworkListener, UpdateListener,MsgListener,ICallInfoDesc, IMsgCallBack,IAddrUpdate, DialListener,DialogInterface.OnClickListener {

	public final static String TAG = "HomeActivity";
	private final static String TENCENT_BUGLY_APPID = "900021303";
	protected static final int GPS_REQUEST_CODE = 1;
	private final static int OVERLAY_REQUEST_CODE = 10;
	private final static int WRITE_SETTINGS_REQUEST_CODE = 11;
	public final static String KEY_HOME = "HomeActivity";
	public final static String KEY_NAME_ISFIRST = "isFirstLogin";

	private TextView mUserName;
	private ImageView mSettingsImageView;

	private GroupcallStateLayout mNewNotificationLayout;

	private TextView message_num;

	private OfflineStateLayout mOfflineStateLayout;

	private FragmentManager mFragmentManager;
	private FragmentPagerAdapter mPagerAdapter;
	private HomeViewPager mViewPager;
	private List<Fragment> list = new ArrayList<Fragment>();
	private PTTLayout mNewPtt;

	private Product product;
	private McIdInfo myInfo;
	private ContactFragment contactFragment;
	//	private MapFragment mapFragment;
	private MessageFragment messageFragment;
	private WorkspaceFragment workspaceFragment;

	private LocationManager mLocationManager;

	private GCallEventAdapter callEventAdapter = null;

	private SharedPreferences mSharedPreferences;
	private WakeLock wakeLock;

	//	private boolean isLoadAddressSuc = false;
	private boolean isKeepAlive = true;
	private AddrInfo peerAddrInfo = null;

	/** permission request 2019/07/15 **/
	private static final int PERMISSION_REQUEST_STORAGE = 1;
	private List<String> mPermissionList = new ArrayList<String>();
	private String[] mPermissions = new String[] {
			Manifest.permission.CHANGE_NETWORK_STATE,
			Manifest.permission.CALL_PHONE,
			Manifest.permission.INTERNET,
			Manifest.permission.MODIFY_AUDIO_SETTINGS,
			Manifest.permission.READ_PHONE_STATE,
			Manifest.permission.RECEIVE_BOOT_COMPLETED,
			Manifest.permission.WRITE_CONTACTS,
			Manifest.permission.WAKE_LOCK,
			Manifest.permission.WRITE_EXTERNAL_STORAGE,
			Manifest.permission.BLUETOOTH,
			Manifest.permission.BLUETOOTH_ADMIN,
			Manifest.permission.USE_SIP,
			Manifest.permission.CAMERA,
			Manifest.permission.ACCESS_COARSE_LOCATION,
			Manifest.permission.ACCESS_FINE_LOCATION,
			Manifest.permission.RECORD_AUDIO,
			Manifest.permission.READ_EXTERNAL_STORAGE,
			Manifest.permission.CAMERA
	};

	//	private int[] tabImageList = {
//			R.drawable.tab_message_select
//			, R.drawable.tab_map_select
//			, R.drawable.tab_contact_select
//			, R.drawable.tab_workspace_select
//	};
	private int[] tabImageList = {
			R.drawable.tab_contact_select
			, R.drawable.tab_message_select
			, R.drawable.tab_workspace_select
	};

	private final ContentObserver mGpsMonitor = new ContentObserver(new Handler()) {

		@Override
		public void onChange(boolean selfChange) {
			// TODO Auto-generated method stub
			super.onChange(selfChange);

			if(mLocationManager != null){
				boolean enable = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

				Log.d(TAG, "onChange GPS state");
				if(enable){
					if(product != null){
						product.startServer(ProductConst.Func_Local);
					}

				}else{
					if(product != null){
						product.stopServer(ProductConst.Func_Local);
					}
				}
			}
		}

	};


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		Log.d(TAG, "onCreate");
		Window window = getWindow();
		window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
		window.setStatusBarColor(getResources().getColor(R.color.app_theme_color_primary));
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home_layout);

		initView();
		initData(savedInstanceState);

		ScreenManager.getScreenManager().pushActivity(HomeActivity.this);

		mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

		// 注册广播接收�?
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(SysApplication.GROUP_CREATE_RESULT_ACTION);
		mResultReceiver = new ResultReceiver();
		registerReceiver(mResultReceiver, intentFilter);

		mSharedPreferences = getSharedPreferences(KEY_HOME, Context.MODE_PRIVATE);

		requestWakeLock();
	}

	@Override
	protected void onDestroy() {
		Log.d(TAG, "onDestroy");
		super.onDestroy();
		this.releaseWakeLock();
		unregisterReceiver(mResultReceiver);
	}

	@Override
	public void onTrimMemory(int level) {
		// TODO Auto-generated method stub
		super.onTrimMemory(level);
		Log.d(TAG,"onTrimMemory level = " + level);
	}

	private void initView(){

		mSettingsImageView = (ImageView)findViewById(R.id.settings_btn);
		mSettingsImageView.setOnClickListener(this);
		mUserName = (TextView)findViewById(R.id.my_name);

		// 通话状态提示栏
		mNewNotificationLayout = (GroupcallStateLayout)findViewById(R.id.notification_new);
		message_num = (TextView)findViewById(R.id.message_num);
		mOfflineStateLayout = (OfflineStateLayout) findViewById(R.id.offline_status_layout);
		mViewPager = (HomeViewPager) findViewById(R.id.fragment_content);
		// PTT模块
		mNewPtt = (PTTLayout)findViewById(R.id.ptt_new);
	}

	private void initIndicator(){
		MagicIndicator magicIndicator = (MagicIndicator) findViewById(R.id.magic_indicator);
		CommonNavigator commonNavigator = new CommonNavigator(this);
		commonNavigator.setAdjustMode(true);
		commonNavigator.setAdapter(new CommonNavigatorAdapter() {

			@Override
			public int getCount() {
				return list.size();
			}

			@Override
			public IPagerTitleView getTitleView(Context context, final int index) {
				CommonPagerTitleView commonPagerTitleView = new CommonPagerTitleView(context);

				// load custom layout
				View customLayout = LayoutInflater.from(context).inflate(R.layout.magic_tab_layout, null);
				final ImageView titleImg = (ImageView) customLayout.findViewById(R.id.title_img);
				titleImg.setImageResource(tabImageList[index]);
				commonPagerTitleView.setContentView(customLayout);
				commonPagerTitleView.setOnPagerTitleChangeListener(new CommonPagerTitleView.OnPagerTitleChangeListener() {

					@Override
					public void onSelected(int index, int totalCount) {
						//全白
						titleImg.setImageAlpha(255);
					}

					@Override
					public void onDeselected(int index, int totalCount) {
						//半透明
						titleImg.setImageAlpha((int)(255*0.7));
					}

					@Override
					public void onLeave(int index, int totalCount, float leavePercent, boolean leftToRight) {
					}

					@Override
					public void onEnter(int index, int totalCount, float enterPercent, boolean leftToRight) {
					}
				});

				commonPagerTitleView.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						mViewPager.setCurrentItem(index);
					}
				});

				return commonPagerTitleView;
			}

			@Override
			public IPagerIndicator getIndicator(Context context) {
				TriangularPagerIndicator indicator = new TriangularPagerIndicator(context);
				indicator.setLineHeight(0);
				indicator.setLineColor(Color.WHITE);
				return indicator;
			}
		});
		magicIndicator.setNavigator(commonNavigator);
		ViewPagerHelper.bind(magicIndicator, mViewPager);
	}

	private void initData(Bundle savedInstanceState){
		mFragmentManager = getSupportFragmentManager();
		myInfo = getMyLoginInfo();

		if(savedInstanceState !=null){
			List<Fragment>  fragments = mFragmentManager.getFragments();
			for(int i = 0 ; i < fragments.size() ; i++)
			{
				Log.d(TAG," fragment = "+fragments.get(i));
				Fragment fragment = fragments.get(i);
				if(fragment instanceof ContactFragment){
					contactFragment = (ContactFragment) fragments.get(i);
				}
//				else if(fragment instanceof MapFragment){
//					mapFragment = (MapFragment) fragments.get(i);
//				}
				else if(fragment instanceof MessageFragment){
					messageFragment = (MessageFragment)fragments.get(i);
				}
				else if(fragment instanceof WorkspaceFragment){
					workspaceFragment = (WorkspaceFragment)fragments.get(i);
				}

			}

		}else{
			AddrInfo info = null;
			if(myInfo != null)
			{
				info = myInfo.toAddrInfo();
			}
			contactFragment = new ContactFragment(this,info,this);
//			mapFragment = new MapFragment(info);
			messageFragment = new MessageFragment(this,info,this,this);
			workspaceFragment = new WorkspaceFragment(this);
		}

		updateMyName();
		list.add(contactFragment);
		list.add(messageFragment);
//		list.add(mapFragment);
		list.add(workspaceFragment);

		if(mFragmentManager != null){
			mPagerAdapter = new ViewPagerAdapter(mFragmentManager, list);
			mViewPager.setAdapter(mPagerAdapter);
			mViewPager.setOffscreenPageLimit(list.size());
			initIndicator();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		Log.d(TAG, "onResume");
		checkPermission();

		this.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				goProcess();
			}
		});
		if(product == null){
			SysApplication app = ((SysApplication) getApplicationContext());
			this.product = app.getProduct();
		}
		if( product != null)
		{
			if(callEventAdapter == null)
			{
				callEventAdapter = product.getGCallEventAdapter();
			}
			callEventAdapter.setCallInfoDesc(this);

			mNewPtt.setCallAdapter(callEventAdapter);
			mNewPtt.setDialListener(this);
//			boolean hasActivieGroupVideoCall = callEventAdapter.hasActivieGroupVideoCall();
//			Log.d(TAG, "onResume hasActivieGroupVideoCall = " + hasActivieGroupVideoCall);
//			mNewPtt.showCallBtn(hasActivieGroupVideoCall);
		}
		printSrceenInfo();
	}



//	private void updateOnlineState(){
//		if(product == null){
//			SysApplication app = ((SysApplication) getApplicationContext());
//			this.product = app.getProduct();
//		}
//
//		if(product!=null
//				&& myInfo != null){
//			AddrOperator operator = (AddrOperator)product.getOperator(ProductConst.Func_Addr);
//			List<GroupInfo> list = operator.getGroupListAndUserList();
//			if(contactFragment != null) {
//				contactFragment.updateData(list);
//			}
//			Log.d(TAG, "updateOnlineState list = " + list);
//		}
//	}

	private void goToSomeActivityByInfo(SysStateInfo sysStateInfo){
		Log.d(TAG, "goToSomeActivityByInfo sysStateInfo = " + sysStateInfo);
		ScreenManager.getScreenManager().popAllActivityExceptOne(HomeActivity.class);
		if(sysStateInfo != null){
			int state = sysStateInfo.getState();
			int cause = sysStateInfo.getCause();
			if(SysStateInfo.SysState_HttpGetSucState == state
					&& SysStateInfo.Cause_Suc != cause)
			{
				goToLogin();
				return;
			}
			//			else if(SysStateInfo.SysState_InitState == state
			//					&& SysStateInfo.Cause_Suc != cause)
			//			{
			//				goToLogin();
			//				return;
			//			}

		}
	}

	private void goToLogin()
	{
		Intent intent = new Intent();
		intent.setClass(HomeActivity.this, Login.class);
		//		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent);
	}


	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		Log.d(TAG, "onPause");
		getContentResolver().unregisterContentObserver(mGpsMonitor);
//		doPttOff(true);
		SysApplication app = ((SysApplication) getApplicationContext());
		this.product = app.getProduct();

		if(this.product !=null){
			product.setNetworkListener(null);
			product.setUpdateListener(null);
			product.setSysListener(this.getClass().getName(),null);
//			product.setAddrListener(null);
			//			product.setLbsListener(null);
			//product.setMsgListener(null);
		}
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onPause();
		Log.d(TAG, "onStop");

		if(callEventAdapter != null)
		{
			callEventAdapter.setCallInfoDesc(null);
			resetPttLayout();
			callEventAdapter = null;
			if(mNewPtt != null)
			{
				mNewPtt.onStop();
			}
		}
	}

	@Override
	public void onClick(View v) {
		ScreenManager.getScreenManager().popAllActivityExceptOne(HomeActivity.class);
		if(R.id.settings_btn == v.getId()){
			Intent intent = new Intent(HomeActivity.this,
					SettingActivity.class);
			startActivity(intent);
			overridePendingTransition( R.anim.in_from_left, R.anim.out_to_right );
		}
	}

	private void doPttOff(boolean isMust)
	{
		Log.d(TAG, "doPttOff");

		if(callEventAdapter != null)
		{
			callEventAdapter.onPtt(Const.MSG_TALK_OFF, true,false,false,false);
		}
	}

	@Override
	public void showTab(boolean showOrHide) {
		// TODO Auto-generated method stub

		mViewPager.setScrollFlag(showOrHide);
	}

	@Override
	public void onFunc(int type, String numStr) {
		Log.d(TAG, "onFunc type = " + type + " numStr = " + numStr);
		if(product == null)
		{
			SysApplication app = ((SysApplication) getApplicationContext());
			this.product = app.getProduct();
		}
		if(numStr != null
				&& numStr.trim().length() > 0)
		{
			if (DialListener.DialFunc_Call == type) {
				this.peerAddrInfo = product.getUserInfoByNum(numStr);
				String item1 = getString(R.string.single_call_voice);
				String item2 = getString(R.string.single_call_video);
				String[] list = new String[]{item1,item2};
				UiDlg.showListDialog(this, list, this);
			} else if (DialListener.DialFunc_Msg == type) {
				if (numStr.equals("210")
						|| numStr.equals("299")) {
					String nameStr = numStr;
					numStr = "50" + numStr;
					AddrInfo peerAddrInfo = new AddrInfo(AddrInfo.GroupType_Normal, nameStr, numStr, 0);
					Intent intent = new Intent(this, SessionActivity.class);
					intent.putExtra(SessionActivity.KEY, peerAddrInfo);
					this.startActivity(intent);
				} else {
					AddrInfo peerAddrInfo = product.getUserInfoByNum(numStr);
					Intent intent = new Intent(this, SessionActivity.class);
					intent.putExtra(SessionActivity.KEY, peerAddrInfo);
					this.startActivity(intent);
				}
			}
		}
	}

	@Override
	public void onClick(DialogInterface dialog, int which) {
		Log.d(TAG, "onClick which = " + which);
		if(product == null)
		{
			SysApplication app = ((SysApplication) getApplicationContext());
			this.product = app.getProduct();
		}
		if(this.peerAddrInfo != null)
		{
			boolean hasVideo = false;
			if(which == 1)
			{
				hasVideo = true;
			}
			product.getPCallEventAdapter().makePrivateCall(peerAddrInfo, CallAttr.CallType_Private,hasVideo,false,"");
		}

	}

	class ViewPagerAdapter extends FragmentPagerAdapter{

		private List<Fragment> list;

		public ViewPagerAdapter(FragmentManager fm , List<Fragment> list) {
			super(fm);
			// TODO Auto-generated constructor stub
			this.list = list;
		}

		@Override
		public Fragment getItem(int location) {
			// TODO Auto-generated method stub
			return list.get(location);
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public CharSequence getPageTitle(int position) {
			// TODO Auto-generated method stub
			return super.getPageTitle(position);
		}
	}

	@Override
	public void onUpdate(int state) {
		// TODO Auto-generated method stub

	}

	@Override
	public void networkChange(boolean isconnected) {
		Log.d(TAG, "networkChange isconnected = " + isconnected);
		// TODO Auto-generated method stub
		if(!isconnected)
		{
			this.runOnUiThread(new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					resetPttLayout();
					setIsOnlineIconState(false,getString(R.string.offline_title));
//					updateOnlineState();
				}
			});
		}

	}

	private boolean checkGpsEnable(){
		if(mLocationManager != null){
			return mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
		}
		return false;
	}

	private void openGpsSettings(){

		new Throwable().printStackTrace();

		boolean isGPSenable = checkGpsEnable();
		Log.d(TAG, "isGPSenable = "+isGPSenable);
		/*if(isGPSenable){
			if(product != null){
				product.startServer(ProductConst.Func_Local);
			}
		}else{*/

		if(mSharedPreferences.getBoolean(KEY_NAME_ISFIRST, false)){
			return;
		}

		OnClickListener okListener = new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
				startActivityForResult(intent, GPS_REQUEST_CODE);
				return;
			}
		};

		OnClickListener cancelListener = new OnClickListener() {

			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
				CommDlg.showToast(HomeActivity.this, R.string.cannot_use_location);
				return;
			}
		};


		CommDlg.showNormalDlg(this, null, getResources().getString(R.string.please_open_gps), okListener, cancelListener);

		mSharedPreferences.edit().putBoolean("isFirstLogin", true).commit();

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		Log.d(TAG, "onActivityResult");
		if(GPS_REQUEST_CODE == requestCode){
			Log.d(TAG, "onActivityResult");
			if(!checkGpsEnable()){
				CommDlg.showToast(HomeActivity.this, R.string.cannot_use_location);
			}else{
				if(product != null){
					product.startServer(ProductConst.Func_Local);
				}
				//openGpsSettings();
			}
		}else if(OVERLAY_REQUEST_CODE == requestCode){

			Log.d(TAG, "overlay result = "+resultCode);
		}else if(WRITE_SETTINGS_REQUEST_CODE == requestCode){
			Log.d(TAG, "write settings result = "+resultCode);
		}
	}

	private void setIsOnlineIconState(boolean isOnline,String offlineDesc){
		Log.d(TAG, "setIsOnlineIconState isOnline = " + isOnline);
		if(isOnline){
			mOfflineStateLayout.setVisibility(View.GONE);
		}else{
			mOfflineStateLayout.setVisibility(View.VISIBLE);
			mOfflineStateLayout.setOfflinDesc(offlineDesc);
			//			mOnlineStateLayout.setVisibility(View.GONE);
		}
//		if(mapFragment != null) {
//			mapFragment.setStatusOnLine(isOnline);
//		}
	}


	@Override
	public void onSysState(SysStateInfo stateInfo) {
		// TODO Auto-generated method stub
		Log.d(TAG, "onSysState stateInfo = " + stateInfo);
		int state = stateInfo.getState();
		int cause = stateInfo.getCause();

		if(SysStateInfo.SysState_SvrStartState == state)
		{
			if(SysStateInfo.Cause_Failed != cause
					|| SysStateInfo.Cause_Timeout == cause
					|| SysStateInfo.Cause_Publish_None == cause
					|| SysStateInfo.Cause_Password == cause)
			{
				String errStr = CauseCont.getAuthErrStr(cause, HomeActivity.this);
				CommDlg.showToast(HomeActivity.this, errStr);
				goToLogin();
			}
		}
		else if(SysStateInfo.SysState_SipAuthSucState == state)
		{
			//			loadAddrList();
			setIsOnlineIconState(true,"");
		}
		else if(SysStateInfo.SysState_SvrStopState == state)
		{
			setIsOnlineIconState(false,getString(R.string.offline_title));
		}
		else if(SysStateInfo.SysState_SvrStartState == state)
		{
			setIsOnlineIconState(false,getString(R.string.offline_logining));
		}
	}

	@Override
	public void onErrer(String str)
	{}
//	@Override
//	public void onAddrUpt() {
//		// TODO Auto-generated method stub
//		this.runOnUiThread(new Runnable() {
//			@Override
//			public void run() {
//				// TODO Auto-generated method stub
//				updateOnlineState();
//			}
//		});
//	}
//
//	@Override
//	public void onOnlineUpt() {
//		// TODO Auto-generated method stub
//		this.runOnUiThread(new Runnable() {
//			@Override
//			public void run() {
//				// TODO Auto-generated method stub
//				updateOnlineState();
//			}
//		});
//	}

//	@Override
//	public void onAddrUptResult(boolean isSuc) {
//		// TODO Auto-generated method stub
//		Log.d(TAG, "onAddrUptResult isSuc = " + isSuc);
//		if(isSuc)
//		{
//			this.runOnUiThread(new Runnable() {
//				@Override
//				public void run() {
//					// TODO Auto-generated method stub
//					updateAddrList();
//				}
//			});
//		}
//	}
//	@Override
//	public void onOnlineUptResult(boolean isSuc) {
//		// TODO Auto-generated method stub
//		Log.d(TAG, "onResult isSuc = " + isSuc);
//		if(isSuc)
//		{
//			this.runOnUiThread(new Runnable() {
//				@Override
//				public void run() {
//					// TODO Auto-generated method stub
//					updateOnlineState();
//				}
//			});
//
//		}
//	}

	//	@Override
	//	public void recvNewReport() {
	//		// TODO Auto-generated method stub
	//		Log.d(TAG, "recvNewReport");
	//		
	//		this.runOnUiThread(new Runnable() {
	//			@Override
	//			public void run() {
	//				// TODO Auto-generated method stub
	//				updateOnlineState();
	//			}
	//		});
	//	}
	@Override
	public void receiveMsg() {
		// TODO Auto-generated method stub
		//UiDlg.createWarningDialog(this, causeStr, R.drawable.black_face).show();
		Log.d(TAG, "receiveMsg");
		this.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				updateHistoryInfoList();
			}
		});
	}

	@Override
	public void onKeepAlive(final boolean isconnected) {
		// TODO Auto-generated method stub
		Log.d(TAG, "onKeepLive isKeepAlive = " + isKeepAlive + " isconnected = " + isconnected);
		if(isKeepAlive != isconnected)
		{
			this.runOnUiThread(new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					if(!isconnected)
					{
						resetPttLayout();
						showPttLayout(false);
						setIsOnlineIconState(false,getString(R.string.offline_title));
					}
					else
					{
						setIsOnlineIconState(true,"");
					}
				}
			});
		}

		//		if(isconnected
		//				|| isKeepAlive != isconnected)
		//		{
		//			if(product != null)
		//			{
		//				String svrIp = product.getSysConfig().getServerInfo().getServerIp();
		//				if(svrIp != null)
		//				{
		//					AddrOperator op = (AddrOperator)product.getOperator(ProductConst.Func_Addr);
		//					op.loadOnlineState(svrIp, this);
		//				}
		//			}
		//		}
//		updateOnlineState();
		this.isKeepAlive = isconnected;
	}
	@Override
	public void onForceDetach() {
		// TODO Auto-generated method stub

	}
	public McIdInfo getMyLoginInfo()
	{
		if(product == null)
		{
			SysApplication app = ((SysApplication) getApplicationContext());
			this.product = app.getProduct();
		}
		if(product == null){
			return null;
		}else{
			return product.getMcpttLoginInfo().getMcIdInfo();
		}
	}
	public AddrInfo getCurGroupInfo()
	{
		Log.d(TAG, "getCurGroupInfo 1");
		if(product == null)
		{
			Log.d(TAG, "getCurGroupInfo 2");
			SysApplication app = ((SysApplication) getApplicationContext());
			this.product = app.getProduct();
		}
		if(product != null)
		{
			AddrInfo info = product.getCurGroupInfo();
			Log.d(TAG, "getCurGroupInfo info = "+info);
			return info;
		}
		return null;
	}
	public void setDefaultGroupInfo(AddrInfo info)
	{
		Log.d(TAG, "setDefaultGroupInfo info = " + info);
		if(product == null)
		{
			SysApplication app = ((SysApplication) getApplicationContext());
			this.product = app.getProduct();
		}
		if(product != null)
		{
			product.setDefaultGroupInfo(info);
		}
		if(contactFragment != null)
		{
			contactFragment.updateAddrList(false);
		}
//		loadAddressAndOnline();
		updateHistoryInfoList();
	}
	/** permission request 2019/07/15 **/

	/** 鏉冮檺妫�鏌ヤ笌鐢宠�?**/
	private void checkPermission() {
		if (Build.VERSION.SDK_INT >= 23)
		{
			mPermissionList.clear();
			for (String permission : mPermissions)
			{
				if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED)
				{

					mPermissionList.add(permission);
				}
			}

			Log.d(TAG, "mPermissionList = "+mPermissionList);
			if (!mPermissionList.isEmpty()) {
				String[] reqpermissions = mPermissionList.toArray(new String[mPermissionList.size()]);
				requestPermissions(reqpermissions, PERMISSION_REQUEST_STORAGE);

			} else if(!Settings.canDrawOverlays(getApplicationContext())){
				startActivityForResult(new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:"+getPackageName())), OVERLAY_REQUEST_CODE);

			}
			//			else if(!Settings.System.canWrite(getApplicationContext())){
			//				Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
			//				intent.setData(Uri.parse("package:"+getPackageName()));
			//				startActivityForResult(intent, WRITE_SETTINGS_REQUEST_CODE);
			//
			//			} 
			else{

				/*if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) 
				{
					String[] requestPermission = new String[1];
					requestPermissions(Manifest.permission.ACCESS_COARSE_LOCATION, 0);
				}*/

				((SysApplication) getApplication()).creatProduct();
			}
		}else{
			((SysApplication) getApplication()).creatProduct();
		}
	}

	@Override
	public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
		boolean grant = true;
		if (requestCode == PERMISSION_REQUEST_STORAGE) {
			for (int i = 0; i < grantResults.length; i++) {
				if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
					grant = false;
					boolean showRequestPermission = shouldShowRequestPermissionRationale(permissions[i]);
					if (showRequestPermission) {
						Intent intent = new Intent();
						intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
						intent.setData(Uri.fromParts("package", getPackageName(), null));
						startActivity(intent);
						finish();
					}
				}
			}

			if(!Settings.canDrawOverlays(getApplicationContext())){
				grant = false;
			}

			if (grant) {
				((SysApplication) getApplication()).creatProduct();
			}
		}
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
	}

	private ResultReceiver mResultReceiver;

	public class ResultReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (SysApplication.GROUP_CREATE_RESULT_ACTION.equals(action)) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						goProcess();
					}
				});
			}
		}
	}

	private void goProcess() {
		if(product == null)
		{
			SysApplication app = ((SysApplication) getApplicationContext());
			this.product = app.getProduct();
		}

		if(product != null){
			product.setNetworkListener(this);
			product.setUpdateListener(this);
			product.setSysListener(this.getClass().getName(),this);

//			product.setAddrListener(this);

			SysStateInfo info = product.getSysStateInfo();
			Log.d(TAG, "goProcess info = "+info);
			if(info == null){
				this.setIsOnlineIconState(false,getString(R.string.offline_title));
			}
			else if(info != null && info.getState() == SysStateInfo.SysState_SipPulishSucState){
				this.setIsOnlineIconState(true,"");
			}else{
				this.setIsOnlineIconState(false,getString(R.string.offline_title));
			}

//			CrashReport.initCrashReport(HomeActivity.this.getApplicationContext(),TENCENT_BUGLY_APPID, false);
//			CrashReport.setUserId(product.getMcpttLoginInfo().getMcIdInfo().getMcId());

			SysStateInfo sysInfo = product.getSysStateInfo();
			goToSomeActivityByInfo(sysInfo);

			getContentResolver().registerContentObserver(Settings.Secure.getUriFor(Settings.System.LOCATION_PROVIDERS_ALLOWED), false, mGpsMonitor);

			boolean isOnLine = product.getOperator(ProductConst.Func_Sys).isOnLine();
			Log.d(TAG, "initData isOnLine = " + isOnLine);
			if(isOnLine) {
				this.setIsOnlineIconState(isOnLine,"");
			}
			else
			{
				this.setIsOnlineIconState(false,getString(R.string.offline_title));

			}

//			updateOnlineState();

			myInfo = product.getSysConfig().getMcInfo();
			if(myInfo != null
					&& myInfo.getName().equals("")) {
				String num = myInfo.getAddrId();
				AddrInfo userInfo = product.getUserInfoByNum(num);
				Log.d(TAG, "initData userInfo = " + userInfo);
				if (userInfo != null) {
					String name = userInfo.getName();
					product.getSysConfig().setMcpttLoginName(name);
				}
			}

			myInfo = getMyLoginInfo();

			if(contactFragment !=null){
				contactFragment.setMyLoginInfo(myInfo.toAddrInfo());
			}

//			if(mapFragment !=null){
//				mapFragment.setMyLoginInfo(myInfo);
//			}

			updateMyName();
		}
	}

	private void updateMyName(){
		if(myInfo != null){
			mUserName.setText(myInfo.getDscp());
		}
	}
//	@Override
//	public void incomingCall(String callKey, AddrInfo incomingInfo)
//	{
//		Log.d(TAG, "updateCallUser callKey = " + callKey + " incomingInfo = " + incomingInfo);
//		this.runOnUiThread(new Runnable() {
//			@Override
//			public void run() {
//				// TODO Auto-generated method stub
//				String desc = incomingInfo.getDscp();
//				mNewNotificationLayout.setGroupName(desc);
//				String str = getString(R.string.group_call_incomming);
//				mNewNotificationLayout.setState(str);
//				mNewNotificationLayout.setVisibility(View.INVISIBLE);
//				mNewPtt.showAcceptBtn();
//				showPttLayout(true);
//			}
//		});
//	}

	@Override
	public void updateCallUser(String callKey,final boolean isShow,final String callInfoDesc) {
		// TODO Auto-generated method stub
		Log.d(TAG, "updateCallUser callKey = " + callKey + " isShow = " + isShow + " callInfoDesc = " + callInfoDesc);
		this.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				mNewNotificationLayout.setGroupName(callInfoDesc);
				showPttLayout(isShow);
			}
		});
	}

	private void resetPttLayout(){
		Log.d(TAG, "resetPttLayout");
		mNewNotificationLayout.setVisibility(View.GONE);
		mNewNotificationLayout.resetView();

		mNewPtt.clearState();
	}

	private void showPttLayout(boolean isShow){

		mNewNotificationLayout.setVisibility(isShow ? View.VISIBLE : View.GONE);

		mNewPtt.showCallBtn(isShow);
	}

	@Override
	public void updateCallInfoDesc(String callKey,int callState,final String callInfoDesc) {
		// TODO Auto-generated method stub
		Log.d(TAG, "updateCallInfoDesc callKey = " + callKey + " callInfoDesc = " + callInfoDesc);
		this.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				mNewNotificationLayout.setState(callInfoDesc);
			}
		});
	}
	@Override
	public void updateFloorInfoDesc(String callKey, int speakState, String floorInfoDesc) {

	}
	@Override
	public void updateFloorState(String callKey,int speakState,boolean hasVoice)
	{}

	@Override
	public void updateSecDesc(String callKey, final String timeStr) {
		// TODO Auto-generated method stub
		this.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				mNewNotificationLayout.updateTimer(timeStr);
				showPttLayout(true);
			}
		});
	}
	@Override
	public void updateHistoryInfoList()
	{

		Log.d(TAG, "updateHistoryInfoList");


		if(product == null){
			SysApplication app = ((SysApplication) getApplicationContext());
			product = app.getProduct();
		}
		if(product != null)
		{
			product.setMsgListener(this,null);
			MsgOperator operator = (MsgOperator)product.getOperator(ProductConst.Func_Msg);
			List<HistoryInfo> list = operator.getHistoryInfoList();
			if(messageFragment != null
					&& list != null
					&& list.size() >= 0)
			{
				int count = getUnReadCount(list);
				updateUnReadCount(count);
				messageFragment.updateHistoryRecords(list);
			}
		}
	}
	@Override
	public boolean delHirstoryRecord(HistoryInfo info) {
		// TODO Auto-generated method stub
		SysApplication app = ((SysApplication) getApplicationContext());
		Product product = app.getProduct();
		MsgOperator operator = (MsgOperator)product.getOperator(ProductConst.Func_Msg);
		String receiverUId = info.getPeerAddrInfo().getAddrId();//.getAddrInfo().getMcId();
		boolean isSuc = operator.delHirstory(receiverUId);
		return isSuc;
	}

	private void updateUnReadCount(int count)
	{
		if(count == 0)
		{
			message_num.setVisibility(View.GONE);
		}
		else if(count > 99)
		{
			message_num.setVisibility(View.VISIBLE);
			message_num.setText("...");
		}
		else
		{
			message_num.setVisibility(View.VISIBLE);
			message_num.setText("" + count);
		}
	}
	private int getUnReadCount(List<HistoryInfo> list)
	{
		int count = 0;
		for(Iterator<HistoryInfo> itor = list.iterator();itor.hasNext();)
		{
			HistoryInfo info = itor.next();
			count = count + info.getUnreadCount();
		}
		return count;
	}



	@Override
	public void onSvrRestart() {
		// TODO Auto-generated method stub

	}
//	@Override
//	public void initConfigSuc(String fileName)
//	{
//		Log.d(TAG, "initConfigSuc fileName = " + fileName);
//		if(UserProfile.FileName_Mcptt.equals(fileName))
//		{
//			myInfo = getMyLoginInfo();
//			updateMyName();
//
//			if(contactFragment !=null){
//				contactFragment.updateAddrList(true);
//			}
//		}
//	}
//	@Override
//	public void initConfigFailed(String fileName,String errStr)
//	{
//		Log.d(TAG, "initConfigFailed fileName = " + fileName);
//	}


	public void requestWakeLock() {
		PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
		wakeLock = powerManager.newWakeLock(
				PowerManager.SCREEN_BRIGHT_WAKE_LOCK
						| PowerManager.ACQUIRE_CAUSES_WAKEUP,
				"com.cloudptt.wp.ui.HomeActivity");
		if (wakeLock != null)
			wakeLock.setReferenceCounted(false);
		if (wakeLock != null && !wakeLock.isHeld()) {
			wakeLock.acquire();
		}
	}

	private void releaseWakeLock()
	{
		if (wakeLock != null && wakeLock.isHeld()) {
			wakeLock.release();
		}
	}

//	public void loadAddrList()
//	{
//		SysConfig config = product.getSysConfig();//.getServerInfo().getServerIp();
//		if(config != null)
//		{
//			AddrOperator op = (AddrOperator)product.getOperator(ProductConst.Func_Addr);
//			op.loadAddress(config, this);//.loadAddressAndOnline(svrIp, this);
//		}
//	}

//	public void loadAddressAndOnline()
//	{
////		String svrIp = product.getSysConfig().getServerInfo().getServerIp();
////		if(svrIp != null)
////		{
////			AddrOperator op = (AddrOperator)product.getOperator(ProductConst.Func_Addr);
////			op.loadOnlineState(svrIp, this);
////		}
//	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if(event.getKeyCode() == KeyEvent.KEYCODE_BACK)
		{
			return true;
		}

		switch (keyCode) {
			case KeyEvent.KEYCODE_VOLUME_UP:
				callEventAdapter.onVol(KeyEvent.KEYCODE_VOLUME_UP);
				break;
			case KeyEvent.KEYCODE_VOLUME_DOWN:
				callEventAdapter.onVol(KeyEvent.KEYCODE_VOLUME_DOWN);
				break;
			case KeyEvent.KEYCODE_VOLUME_MUTE:
				callEventAdapter.onVol(KeyEvent.KEYCODE_VOLUME_MUTE);
				break;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		Log.d(TAG, "onKeyUp keyCode = " + keyCode);
		if(event.getKeyCode() == KeyEvent.KEYCODE_BACK)
		{
			return true;
		}

		switch (keyCode) {
//			case 142:
//				if(callEventAdapter != null)
//				{
//					callEventAdapter.onPtt(Const.MSG_TALK_OFF,false,true);
//				}
//				break;
			case KeyEvent.KEYCODE_VOLUME_UP:
				callEventAdapter.onVol(KeyEvent.KEYCODE_VOLUME_UP);
				break;
			case KeyEvent.KEYCODE_VOLUME_DOWN:
				callEventAdapter.onVol(KeyEvent.KEYCODE_VOLUME_DOWN);
				break;
			case KeyEvent.KEYCODE_VOLUME_MUTE:
				callEventAdapter.onVol(KeyEvent.KEYCODE_VOLUME_MUTE);
				break;
		}
		return super.onKeyUp(keyCode, event);
	}
	/** permission request 2019/07/15 **/
	public void printSrceenInfo()
	{
		DisplayMetrics displayMetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

		int width = displayMetrics.widthPixels; // 获取屏幕宽度（像素）
		int height = displayMetrics.heightPixels; // 获取屏幕高度（像素）
		Log.debug(this.getClass(),"onCreate displayMetrics : " + width + " x " + height);
	}
}
